﻿using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json.Linq;
using SYSoft.Comm;
using SYSoft.Model;
using SYSoft.Model.ViewModels.GateWay;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SYSoft.Controllers.GateWay
{
    public class BasicInfosController : BaseController
    {

        /// <summary>
        /// 获取所有设备信息
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public  MessageModel<List<GateWayInfo>> GetAllGateWayInfo()
        {
           var res = NetFactory.redisPool.ReadAllKeys("NetGate*"); // 查找NetGate开头的key，代表网关
            if(res.IsSuccess)
            {
                List<GateWayInfo> gateWayInfos = new List<GateWayInfo>();
                for (int i = 0; i < res.Content.Length; i++)
                {
                   var res1 = NetFactory.redisPool.ReadHashKey(res.Content[i], "__status");
                    if(res1.IsSuccess)
                    {
                        JObject obj = JObject.Parse(res1.Content);
                        GateWayInfo info = new GateWayInfo
                        {
                            Name = obj["__name"].ToString(),
                            Description = obj["__description"].ToString(),
                            DeviceCount= Convert.ToInt32( obj["__deviceCount"]),
                            //DeviceList= obj["__name"].ToString(),
                            SatrtTime=Convert.ToDateTime( obj["__startTime"]),
                            ActiveTime = Convert.ToDateTime(obj["__activeTime"]),
                        };
                        gateWayInfos.Add(info);
                    }
                }
                if (gateWayInfos.Count > 0) return MessageModel.CreateSuccessResult(gateWayInfos);
                else MessageModel.CreateFailedResult<List<GateWayInfo>>("未查询到创建了网关");

            }
            return MessageModel.CreateFailedResult<List<GateWayInfo>>(res.Message);
        }




        /// <summary>
        /// 下载设备采集信息 到 指定网关
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public MessageModel DownLoadConfig(string gatewayid)
        {
            NetFactory.mqttServer.PublishTopicPayload(gatewayid, "downdeviceconfig", Encoding.UTF8.GetBytes("123456789"));
            return MessageModel.CreateSuccessResult();
        }
    }
}
